package com.lmind.gps;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;

import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.lmind.core.gps.gateway.SmartTerminalGateway;
import com.lmind.core.gps.gateway.TerminalGateway;
import com.lmind.core.gps.terminal.DefaultMessageCodec;
import com.lmind.core.gps.terminal.Terminal;
import com.lmind.core.gps.terminal.message.AbstractMessage;
import com.lmind.core.gps.tm.DefaultTerminalManager;
import com.lmind.core.gps.tm.TerminalManagerListener;
import com.lmind.core.message.MessagePipeIoHandler;
import com.lmind.core.message.MessagePipeIoHandlerConfig;

public class TerminalManagerService {
	
	private DefaultTerminalManager terminalManager;
	
	private SmartTerminalGateway gateway;
	
	private NioSocketAcceptor gatewayAcceptor;
	
	private MessagePipeIoHandler gatewayPipe;
	
	private int gatewayPort = 15443;
	
	
	private NioSocketAcceptor tmAcceptor;
	
	private MessagePipeIoHandler tmPipe;
	
	private int tmPort = 15444;
	
	public void init() {
		
		gatewayAcceptor = new NioSocketAcceptor();
		gatewayPipe = new MessagePipeIoHandler();
		gateway = new SmartTerminalGateway();
		
		gatewayAcceptor.setHandler(gatewayPipe);
		
		gatewayPipe.setIoService(gatewayAcceptor);
		MessagePipeIoHandlerConfig config = new MessagePipeIoHandlerConfig();
		config.setTimeout(30);
		gatewayPipe.setConfig(config);
		gatewayPipe.setCodec(new DefaultMessageCodec());
		
		gateway.setMessagePipe(gatewayPipe);
		
		
		terminalManager = new DefaultTerminalManager();
		ArrayList<TerminalGateway> gateways = new ArrayList<TerminalGateway>();
		gateways.add(gateway);
		terminalManager.setGateways(gateways);
		terminalManager.addTerminalManagerListener(new TmListener());
		
		
		tmAcceptor = new NioSocketAcceptor();
		tmPipe = new MessagePipeIoHandler();
		
		tmAcceptor.setHandler(tmPipe);
		
		config = new MessagePipeIoHandlerConfig();
		config.setTimeout(30);
		tmPipe.setConfig(config);
		tmPipe.setCodec(new DefaultMessageCodec());
	}
	
	void start() throws IOException {
		gatewayAcceptor.bind(new InetSocketAddress(gatewayPort));
	}
	
	
	class TmListener implements TerminalManagerListener {

		@Override
		public void message(Terminal terminal, AbstractMessage message) {
			// TODO Auto-generated method stub
			
		}
	}
}
